#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

import time
import urllib
import urllib2
import logging
import sys
import os
import threading
from optparse import OptionParser
from AEConnector import AEConnector

_FOOTBALL_EVENT = '/football_scores/event/'


def remove_repetitions(list):
    """ Remove the repeated values inside a list """
    list_aux = []
    while (list != []):
        element = list.pop()
        if element not in list:
            list_aux.append(element)
    return list_aux

class Feeder_Stub(object):

    def __init__(self, connector):
        self.url = connector.url_base + _FOOTBALL_EVENT
        self.connector = connector        

    def run(self):
        values = {'home': 'Banfield',
                  'visitor': 'Tigre',
                  'scorer': 'Probando',
                  'score': '4-3'}
        data = urllib.urlencode(values)
        users = self.getUsers(data)
        if (users != None):
            self.courierBurst(remove_repetitions(users.split('&')), data)
        
    def getUsers(self, message):
        # When a goal is scored, this method notifies it and receives a list
        # of users that belong to the event.
        tries = 3
        users = None
        while (tries>0):
            # The while is for preventing errors. Where there is some kind of internal
            # sever error, try again. Just 3 attemps.
            try:
                users_f = self.connector.sendRequest(self.url, message)
                users = users_f.read()
                if users == '':
                    users = None
                break
            except urllib2.HTTPError, e:
                logging.error("%s: The users couldn't be gathered because of a server exception: %s" % (message, e))
                if tries == 0:
                    logging.error("No more tries")
                    break
            tries = tries - 1
        return users

    def courierBurst(self, users, message):
        logging.info(users)
        for u in users:
            thread = Courier(u, message, self.connector, self.url)
            thread.start()

class Courier(threading.Thread):
    
    def __init__(self, user, message, connector, url):
        threading.Thread.__init__(self)
        self.user = user
        self.message = message
        self.connector = connector
        self.url = url

    def run(self):
        tries = 3
        while (tries>0):
            # The while is for preventing errors. Where there is some kind of internal
            # sever error, try again. Just 3 attemps.
            try:
                response = self.connector.sendRequest(self.url, self.message + '&user=%s' % self.user)
                break
            except urllib2.HTTPError, e:
                logging.error("Error in a Courier: %s: %s" % (self.user, e))
                if tries == 0:
                    logging.error("No more tries")
                    break
            tries = tries - 1

            
def main(argv):
    logging.basicConfig(format=("%(asctime)s %(levelname)s %(filename)s:"
                                "%(lineno)s %(message)s "))
    logging.getLogger().setLevel(logging.DEBUG)

    connection = AEConnector(dev_server=True)
    Feeder_Stub(connection).run()

if __name__ == "__main__":
  main(sys.argv)
